package com.hunan.api.catv.service.biz.cps;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.CacheKey;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.enums.BindCardEnum;
import com.hunan.api.catv.entity.enums.DingType;
import com.hunan.api.catv.entity.po.MemberAccountRelated;
import com.hunan.api.catv.entity.vo.MemberVo;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.biz.ding.DingBiz;
import com.hunan.api.catv.service.biz.member.MemberBiz;
import com.hunan.api.catv.service.impl.cps.CpsService;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.Hmacsha256Utils;
import com.hunan.api.catv.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

@Service
public class CpsBiz extends ResultService {

    @Autowired
    CpsService cpsService;

    @Autowired
    CacheBiz cacheBiz;

    @Autowired
    CpsBiz cpsBiz;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    MemberBiz memberBiz;

    @Autowired
    DingBiz dingBiz;

    public ServiceResult getCustomerProductInfo(Integer memberId) {
        MemberVo memberVo = memberBiz.info(memberId);
        String smartCardCode = memberVo.getSmartCardCode();
        if (!ObjectUtils.isEmpty(memberVo) && !ObjectUtils.isEmpty(smartCardCode)) {
            return cpsBiz.getCustomerProductInfo(smartCardCode);
        }
        return buildFail(ConstantsMsg.cps_getUserInfo_fail);
    }

    public ServiceResult queryPaymentInfo(Integer memberId) {
        MemberVo memberVo = memberBiz.info(memberId);
        String smartCardCode = memberVo.getSmartCardCode();
        if (!ObjectUtils.isEmpty(memberVo) && !ObjectUtils.isEmpty(smartCardCode)) {
            return cpsBiz.queryPaymentInfo(smartCardCode);
        }
        return buildFail(ConstantsMsg.cps_paymentInfo_fail);
    }

    public ServiceResult getCustomerProductInfo(String smartCardCode) {
        JsonObject conf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.iptv_service_hall_conf), JsonObject.class);
        if (!ObjectUtils.isEmpty(conf)) {
            String domain = conf.get("domain").getAsString();
            String platform = conf.get("platform").getAsString();
            String secret = conf.get("secret").getAsString();
            Map<String, String> paraMap = new HashMap<String, String>();
            Map<String, String> data = new HashMap<String, String>();
            data.put("platform", platform);
            data.put("smartCardCode", smartCardCode);
            data.put("userCode", "");
            paraMap.put("data", GsonUtils.toJson(data));
            paraMap.put("timestamp", System.currentTimeMillis() + "");
            String sign = Hmacsha256Utils.cpsSign(paraMap, secret);
            paraMap.put("sign", sign);
            JsonObject info = cpsService.getCustomerProductInfo(domain, paraMap);
            if (!ObjectUtils.isEmpty(info)) {
                String status = info.get("status").getAsString();
                if ("0".equals(status)) {
                    JsonObject result = info.get("data").getAsJsonObject();
                    return buildOK(result);
                }
            }
        }
        return buildFail(ConstantsMsg.cps_getUserInfo_fail);
    }

    public ServiceResult queryPaymentInfo(String smartCardCode) {
        JsonObject conf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.iptv_service_hall_conf), JsonObject.class);
        if (!ObjectUtils.isEmpty(conf)) {
            String domain = conf.get("domain").getAsString();
            String platform = conf.get("platform").getAsString();
            String secret = conf.get("secret").getAsString();
            Map<String, String> paraMap = new HashMap<String, String>();
            Map<String, String> data = new HashMap<String, String>();
            data.put("platform", platform);
            data.put("smartCardCode", smartCardCode);
            data.put("userCode", "");
            paraMap.put("data", GsonUtils.toJson(data));
            paraMap.put("timestamp", System.currentTimeMillis() + "");
            String sign = Hmacsha256Utils.cpsSign(paraMap, secret);
            paraMap.put("sign", sign);
            JsonObject info = cpsService.queryPaymentInfo(domain, paraMap);
            if (!ObjectUtils.isEmpty(info)) {
                String status = info.get("status").getAsString();
                if ("0".equals(status)) {
                    JsonObject result = info.get("data").getAsJsonObject();
                    JsonArray paymentInfos = result.get("paymentInfos").getAsJsonArray();
                    if (!ObjectUtils.isEmpty(paymentInfos)) {
                        for (int i = 0; i < paymentInfos.size(); i++) {
                            JsonObject j = paymentInfos.get(i).getAsJsonObject();
                            BigDecimal amount = j.get("amount").getAsBigDecimal().divide(new BigDecimal(100));
                            j.addProperty("amount", amount);
                        }
                    }
                    return buildOK(result);
                }
            }
        }
        return buildFail(ConstantsMsg.cps_paymentInfo_fail);
    }

    /**
     * 校验大屏ca卡号状态
     */
    public ServiceResult queryUserStatus(String smartCardCode) {
        JsonObject conf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.iptv_service_hall_conf), JsonObject.class);
        if (!ObjectUtils.isEmpty(conf)) {
            JsonObject info = cpsService.queryUserStatus(conf.get("domain").getAsString(), getParams(conf, smartCardCode));
            if (!ObjectUtils.isEmpty(info)) {
                String status = info.get("status").getAsString();
                if ("0".equals(status)) {
                    JsonObject result = info.get("data").getAsJsonObject();
                    Integer userStatus = result.get("userStatus").getAsInt();
                    if (0 == userStatus) {
                        return buildOK(true);
                    } else {
                        dingBiz.dingNotify("卡信息无效:" + smartCardCode + "查询状态结果:" + result, DingType.api.getCode());
                        return buildFail(userStatus == 1 ? ConstantsMsg.cps_user_seviece : userStatus == 2 ? ConstantsMsg.cps_user_close : userStatus == 4 ? ConstantsMsg.cps_user_stop_voluntarily : ConstantsMsg.cps_user_associated_shutdown);
                    }
                }
                dingBiz.dingNotify("卡信息无效:" + smartCardCode + "查询状态结果:" + info, DingType.api.getCode());
            }
        }
        return buildFail(ConstantsMsg.cps_user_invaid);
    }

    /**
     * 大屏参数拼接已经签名生成
     */
    public Map<String, String> getParams(JsonObject conf, String smartCardCode) {
        String platform = conf.get("platform").getAsString();
        String secret = conf.get("secret").getAsString();
        Map<String, String> paraMap = new HashMap<String, String>();
        Map<String, String> data = new HashMap<String, String>();
        //data.put("platform", platform);
        if (smartCardCode.indexOf("-") > 0 || smartCardCode.indexOf(":") > 0) {
            data.put("mac", smartCardCode.replace("-", ":"));
        } else if (smartCardCode.contains("HNTV")) {
            data.put("userId", smartCardCode);
        } else {
            data.put("cardId", smartCardCode);
        }
        paraMap.put("data", GsonUtils.toJson(data));
        paraMap.put("timestamp", System.currentTimeMillis() + "");
        String sign = Hmacsha256Utils.cpsSign(paraMap, secret);
        paraMap.put("sign", sign);
        log.info("cps param:{}", paraMap);
        return paraMap;
    }

    /**
     * 获取大屏账号信息
     */
    public ServiceResult queryUserInfo(String smartCardCode) {
        JsonObject conf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.iptv_service_hall_conf), JsonObject.class);
        if (!ObjectUtils.isEmpty(conf)) {
            JsonObject info = cpsService.queryUserInfo(conf.get("domain").getAsString(), getParams(conf, smartCardCode));
            if (!ObjectUtils.isEmpty(info)) {
                String status = info.get("status").getAsString();
                if ("0".equals(status)) {
                    JsonObject result = info.get("data").getAsJsonObject();
                    //大屏账号userid
                    String accountId = result.get("passport") != null ? result.get("passport").getAsString() : "";
                    //ca卡号
                    String cardId = result.get("cardId") != null ? result.get("cardId").getAsString() : "";
                    //mac
                    String mac = result.get("mac") != null ? result.get("mac").getAsString() : "";
                    //盒子设备类型
                    int terminalType = result.get("terminalType") != null ? result.get("terminalType").getAsInt() : null;
                    //BSS里面的客户编号,大屏账号唯一标识,可能为空
                    String stbId = result.get("customerId") != null ? result.get("customerId").getAsString() : "";
                    MemberAccountRelated memberAccountRelated = new MemberAccountRelated();
                    memberAccountRelated
                            .setAccountId(accountId)
                            .setCa(cardId)
                            .setMac(mac)
                            .setTerminalType(terminalType)
                            .setStbid(stbId);
                    return buildOK(memberAccountRelated);
                }
                dingBiz.dingNotify("卡信息无效:" + smartCardCode + "查询状态结果:" + info, DingType.api.getCode());
            }
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("smartCardCode", smartCardCode);
        map.put("resultType", BindCardEnum.INVALID.getCode());
        return buildFail(map, ConstantsMsg.cps_user_invaid);
    }

    public ServiceResult getMobile(String smartCardCode) {
        ServiceResult inforResult = cpsBiz.getCustomerProductInfo(smartCardCode);
        if (inforResult.getStatus()) {
            JsonObject info = GsonUtils.fromJson(inforResult.getData().toString(), JsonObject.class);
            String mobile = info.get("mobile").getAsString();
            if (!ObjectUtils.isEmpty(mobile)) {
                String infoKey = MessageFormat.format(CacheKey.member_cps_info, smartCardCode);
                redisUtils.set(infoKey, mobile, 600);
                return buildOK(mobile);
            }
        }
        return inforResult;
    }
}
